import 'package:flutter/cupertino.dart';
import 'package:flutter_vibrate/flutter_vibrate.dart';

///点击时降低透明度的点击事件
class TapOpacity extends StatefulWidget {
    final Widget child;
    final double opacity;
    final void Function()? onTap;
    final void Function()? onTapDown;
    final void Function()? onTapUp;
    final void Function()? onTapCancel;
    final EdgeInsets? padding;
    const TapOpacity({Key? key,required this.child,this.onTap,this.padding,this.opacity=0.4,this.onTapDown,this.onTapUp,this.onTapCancel}) : super(key: key);

  @override
  _TapOpacityState createState() => _TapOpacityState();
}

class _TapOpacityState extends State<TapOpacity> {

    double opacity=1;


    @override
    void initState() {
        super.initState();
    }

    @override
    Widget build(BuildContext context) {
        return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTapDown: (e)async{
                widget.onTapDown?.call();
                if(widget.onTap!=null){
                    setState(() {
                        opacity=widget.opacity;
                    });
                    Vibrate.feedback(FeedbackType.light);
                }


            },
            onTapUp: (e){
                widget.onTapUp?.call();
                if(widget.onTap!=null){
                    Future.delayed(const Duration(milliseconds: 100),(){
                        setState(() {
                            opacity=1;
                        });
                    });
                }

            },
            onTapCancel: (){
                widget.onTapCancel?.call();
                if(widget.onTap!=null){
                    setState(() {
                        opacity=1;
                    });
                }

            },
            onTap: (){
                if(widget.onTap!=null){
                    Future.delayed(const Duration(milliseconds: 200),(){
                        widget.onTap!();
                    });
                }
            },
            child: Opacity(
                opacity: opacity,
                child: Padding(
                    padding:widget.padding??EdgeInsets.zero,
                    child:widget.child
                )
            ),
        );
    }
}
